package cn.tedu.straw.portal.controller;


import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.ex.StrawException;
import cn.tedu.straw.portal.result.Result;
import cn.tedu.straw.portal.security.LoginUserInfo;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.vo.AnswerListItemVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-11
 */
@Api(tags = "答案相关接口")
@RestController
@RequestMapping("/portal/answer")
@Slf4j
public class AnswerController {

    @Autowired
    private IAnswerService answerService;

    @ApiOperation(value = "写答案")
    @PostMapping("post")
    public Result<Void> postAnswer(@Validated PostAnswerDTO postAnswerDTO, BindingResult bindingResult,
                                   @AuthenticationPrincipal LoginUserInfo loginUserInfo){

        log.debug("发表答案,用户提交的数据: {}",postAnswerDTO);
        log.debug("发表答案,当前登录的用户信息: {}",loginUserInfo);

        if (bindingResult.hasErrors()){
            String error = bindingResult.getFieldError().getDefaultMessage();
            throw new StrawException(error);
        }

        Integer userId = loginUserInfo.getUserId();
        String nickName = loginUserInfo.getNickName();

        answerService.post(postAnswerDTO,userId,nickName);

        return Result.ok();
    }

    @ApiOperation(value = "显示答案以及评论")
    @GetMapping("")
    public Result<List<AnswerListItemVO>> getAnswerList(Integer questionId){
        return Result.ok(answerService.getAnswerList(questionId));
    }

}
